layui.define(['jquery','layer','conf'],function (exports) {
    var $ = layui.jquery;
    var layer = layui.layer;
    var conf = layui.conf;

    var http = {
        base_server: conf.base_server,
        viewVersion: conf.viewVersion,
        pageTabs: conf.pageTabs,
        openTabCtxMenu: conf.openTabCtxMenu,
        maxTabNum: conf.maxTabNum,
        viewPath: conf.viewPath,
        defaultTheme: conf.defaultTheme,
        ok: function(code){
            if(0 == code || 200 == code){
                return true;
            }else{
                return false;
            }
        },
        failMsg: function(msg){
            layer.alert(msg,{icon:2});
        },
        okMsg: function (msg) {
            layer.msg(msg,{icon:1});
        },
        // 获取缓存的token
        getToken: function () {
            return layui.data(conf.tableName).token;
        },
        // 清除token
        removeToken: function () {
            layui.data(conf.tableName, {
                key: 'token',
                remove: true
            });
        },
        // 缓存token
        putToken: function (token) {
            layui.data(conf.tableName, {
                key: 'token',
                value: token
            });
        },
        // 当前登录的用户
        getUser: function () {
            return layui.data(conf.tableName).login_user;
        },
        // 缓存user
        putUser: function (user) {
            layui.data(conf.tableName, {
                key: 'login_user',
                value: user
            });
        },
        getDeptCodeList: function(){
            return layui.data(conf.tableName).deptCodeList;
        },
        putDeptCodeList: function(codeList){
            layui.data(conf.tableName,{
                key: 'deptCodeList',
                value: codeList
            })
        },
        // 判断是否有权限
        hasPerm: function (auth) {
            var auths = http.getUserAuths();
            if (auths) {
                for (var i = 0; i < auths.length; i++) {
                    if (auth == auths[i]) {
                        return true;
                    }
                }
            }
            return false;
        },
        // 获取用户所有权限
        getUserAuths: function () {
            // var authorities = http.getUser().authorities;
            var auths = [];
            /* for (var i = 0; i < authorities.length; i++) {
                auths.push(authorities[i].authority);
            } */
            return auths;
        },
        // ajax请求的header
        getAjaxHeaders: function () {
            var headers = [];
            /* var token = http.getToken();
            if (token) {
                headers.push({
                    name: 'Authorization',
                    value: 'Bearer ' + token.access_token
                });
            } */
            return headers;
        },
        // ajax请求结束后的处理，返回false阻止代码执行
        ajaxSuccessBefore: function (res) {
            if (res.code == 401) {
                http.removeToken();
                layer.msg('登录过期', {icon: 2, time: 1500}, function () {
                    http.reLogin();
                    //location.reload();
                }, 1000);
                return false;
            } else if (res.code == 403) {
                layer.msg('没有访问权限', {icon: 2});
            } else if (res.code == 404) {
                layer.msg('404目标不存在', {icon: 2});
            }
            return true;
        },
        // 路由不存在处理
        routerNotFound: function (r) {
            // location.replace('#/template/error/error-404');
            layer.alert('路由' + location.hash + '不存在', {
                title: '提示',
                skin: 'layui-layer-admin',
                btn: [],
                offset: '30px',
                anim: 6,
                shadeClose: true
            });
        },
        // 判断是否为json
        parseJSON: function (str) {
            if (typeof str == 'string') {
                try {
                    var obj = JSON.parse(str);
                    if (typeof obj == 'object' && obj) {
                        return obj;
                    }
                } catch (e) {
                    console.warn(e);
                }
            }
        },
        // 封装ajax请求
        ajax: function (param) {
            var successCallback = param.success;
            param.success = function (result, status, xhr) {
                result.msg = result.msg || result.message;
                if(result.msg=='timeout'){
                    result.code=-1;
                    result.status=-1;
                    result.msg = '超时';
                }
                // 判断登录过期和没有权限
                var jsonRs;
                if ('json' == param.dataType.toLowerCase()) {
                    jsonRs = result;
                } else {
                    jsonRs = http.parseJSON(result);
                }
                if (jsonRs && http.ajaxSuccessBefore(jsonRs) == false) {
                    return;
                }
                successCallback(result, status, xhr);
            };
            param.error = function (xhr) {
                param.success({
                    code: xhr.status,
                    msg: (xhr.responseJSON && xhr.responseJSON.message) || xhr.statusText
                });
            };
            param.beforeSend = function (xhr) {
                var headers = http.getAjaxHeaders();
                for (var i = 0; i < headers.length; i++) {
                    xhr.setRequestHeader(headers[i].name, headers[i].value);
                }
            };
            param.timeout = 40000;
            param.complete = function (XMLHttpRequest, status) { //请求完成后最终执行参数
                layer.closeAll('loading');
                if (status == 'timeout') {//超时,status还有success,error等值的情况
                    //ajax && ajax.abort();
                    http.failMsg("超时");
                }
            };
            param.cache = false;
            return $.ajax(param);
        },
        // 封装post请求，返回数据类型为json
        post: function (url, data, successCallback) {
            layer.load(2);
            var success = function (result, status, xhr) {
                layer.closeAll('loading');
                if (!http.ok(result.code)) {
                    http.fail(result);
                } else {
                    result.ok = true;
                }
                successCallback && typeof successCallback == 'function' && successCallback(result, status, xhr);
            };
            var contentType = 'application/x-www-form-urlencoded';
            if (typeof data === 'string') {
                contentType = "application/json";
            }
            http.ajax({
                url: conf.base_server + url,
                data: data,
                type: 'POST',
                dataType: 'json',
                contentType: contentType,
                success: success
            });
        },
        // 封装get请求，返回数据类型为json
        get: function (url, data, successCallback) {
            layer.load(2);
            var success = function (result, status, xhr) {
                layer.closeAll('loading');
                if (!http.ok(result.code)) {
                    http.fail(result);
                } else {
                    result.ok = true;
                }
                successCallback && typeof successCallback == 'function' && successCallback(result, status, xhr);
            };
            http.ajax({
                url: conf.base_server + url,
                data: data,
                type: 'GET',
                dataType: 'json',
                success: success
            });
        },
        reLogin: function(){
            layer.open({
                type:2,
                content: 'reLogin.html?v='+conf.viewVersion(),
                shade: false,
                area: ['400px','470px'],
                title: '请重新登录',
                id: 'reLogin'
            });
        },
        fail: function (data, msg) {
            layer.closeAll('loading');
            var res = {};
            if (msg) {
                res.code = data;
                res.msg = msg;
            } else {
                res = data;
            }
            if (-1 == res.code) {
                layer.msg(res.msg, {icon: 2});
                return;
            }
            var msg = res.msg;
            switch (res.code) {
                case(500):
                    msg = msg + ",服务器系统内部错误";
                    break;
                case(401):
                    msg = "请登录";
                    break;
                case(403):
                    msg = "无权限执行此操作";
                    break;
                case(408):
                    msg = "请求超时";
                    break;
                default:
                //msg = res.code;
            }
            if (res.code == 401 || res.code == 403) {  //防止多次弹窗
                http.removeToken();
                http.reLogin();
            } else {
                layer.alert(msg, {icon: 2, time: 10000});
            }
        },
        getCodeList: function(listName,callBack){
            http.get('codelist/listItemByName',{listName:listName},callBack);
        },
        getUrlParams: function(url){
            var re = /([^&=]+)=?([^&]*)/g,
                decodeRE = /\+/g,
                decode = function (str) { return decodeURIComponent( str.replace(decodeRE, " ") ); };

            var params = {}, e;
            var urls = url.split('?');
            if(!urls || urls.length<=1){
                return params;
            }
            var ps = urls[1];
            while ( e = re.exec(ps) ) params[ decode(e[1]) ] = decode( e[2] );
            return params;
        }
    };

    exports('http',http);
});